// SmartUI Studio - 主JavaScript文件

// 全屏切换功能
function initFullscreenToggle() {
    const fullscreenBtn = document.getElementById('fullscreen-btn');
    if (!fullscreenBtn) return;
    
    fullscreenBtn.addEventListener('click', function() {
        toggleFullScreen();
    });
    
    // 监听全屏状态变化，更新按钮图标
    document.addEventListener('fullscreenchange', updateFullscreenButtonIcon);
    document.addEventListener('webkitfullscreenchange', updateFullscreenButtonIcon);
    document.addEventListener('mozfullscreenchange', updateFullscreenButtonIcon);
    document.addEventListener('MSFullscreenChange', updateFullscreenButtonIcon);
    
    // 初始化按钮图标
    updateFullscreenButtonIcon();
}

// 切换全屏状态
function toggleFullScreen() {
    if (!document.fullscreenElement && 
        !document.mozFullScreenElement && 
        !document.webkitFullscreenElement && 
        !document.msFullscreenElement) {
        // 进入全屏
        if (document.documentElement.requestFullscreen) {
            document.documentElement.requestFullscreen();
        } else if (document.documentElement.msRequestFullscreen) {
            document.documentElement.msRequestFullscreen();
        } else if (document.documentElement.mozRequestFullScreen) {
            document.documentElement.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullscreen) {
            document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
        }
    } else {
        // 退出全屏
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }
}

// 更新全屏按钮图标
function updateFullscreenButtonIcon() {
    const fullscreenBtn = document.getElementById('fullscreen-btn');
    if (!fullscreenBtn) return;
    
    const icon = fullscreenBtn.querySelector('i');
    if (!icon) return;
    
    if (document.fullscreenElement || 
        document.mozFullScreenElement || 
        document.webkitFullscreenElement || 
        document.msFullscreenElement) {
        // 全屏状态 - 显示退出全屏图标
        icon.className = 'bi bi-fullscreen-exit';
        fullscreenBtn.setAttribute('title', '退出全屏');
    } else {
        // 非全屏状态 - 显示进入全屏图标
        icon.className = 'bi bi-fullscreen';
        fullscreenBtn.setAttribute('title', '全屏切换');
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化Bootstrap工具提示和弹出框
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 加载初始数据
    loadProjects(); // Initial load without filters
    loadTemplates();
    loadTasks();
    loadDevices();
    loadReports();

    // 添加标签切换事件监听器
    document.getElementById('workspace-tab').addEventListener('click', () => loadProjects()); // Reload projects when tab is clicked
    document.getElementById('template-tab').addEventListener('click', loadTemplates);
    document.getElementById('task-tab').addEventListener('click', loadTasks);
    document.getElementById('device-tab').addEventListener('click', loadDevices);
    document.getElementById('report-tab').addEventListener('click', loadReports);
    if(document.getElementById('new_project')){
        document.getElementById('new_project').addEventListener('click', newProject);
    }
    
    // 初始化项目工作区搜索和筛选功能
    setupProjectWorkspaceFilters();
    
    // 初始化侧边栏折叠功能
    initSidebar();
    
    // 初始化全屏切换功能
    initFullscreenToggle();
});

function setupProjectWorkspaceFilters() {
    const searchInput = document.getElementById('projectSearchInput');
    const ownerFilter = document.getElementById('ownerFilter');
    const typeFilter = document.getElementById('typeFilter');
    const platformFilter = document.getElementById('platformFilter');
    const versionFilter = document.getElementById('versionFilter');
    const startDateFilter = document.getElementById('startDateFilter');
    const endDateFilter = document.getElementById('endDateFilter');

    const applyFilters = () => {
        const params = {};
        if (searchInput.value) params.search = searchInput.value;
        if (ownerFilter.value !== '所有用户') params.owner = ownerFilter.value;
        if (typeFilter.value !== '所有类型') params.type = typeFilter.value;
        if (platformFilter.value !== '所有平台') params.platform = platformFilter.value;
        if (versionFilter.value) params.version = versionFilter.value;
        if (startDateFilter.value) params.start_date = startDateFilter.value;
        if (endDateFilter.value) params.end_date = endDateFilter.value;
        console.log('应用筛选条件:', params);
        loadProjects(params);
    };


    const debouncedApplyFilters = debounce(applyFilters, 500); // 500ms debounce

    if (searchInput) {
        searchInput.addEventListener('input', debouncedApplyFilters);
        searchInput.addEventListener('keypress', (event) => {
            if (event.key === 'Enter') {
                applyFilters(); // Apply immediately on Enter
            }
        });
    }

    // 确保所有过滤器元素都添加了change事件监听器
    [ownerFilter, typeFilter, platformFilter, versionFilter, startDateFilter, endDateFilter].forEach(filterElement => {
        if (filterElement) {
            // 移除可能存在的旧事件监听器
            filterElement.removeEventListener('change', applyFilters);
            // 添加新的事件监听器
            filterElement.addEventListener('change', applyFilters);
            console.log('已为元素添加事件监听器:', filterElement.id);
        } else {
            console.warn('过滤器元素不存在:', filterElement);
        }
    });
}

// 加载项目列表
function loadProjects(filters = {}) {
    let url = '/api/projects?api=get_projects';
    const queryParams = new URLSearchParams(filters).toString();
    if (queryParams) {
        url += '&' + queryParams;
    }

    axios.get(url)
        .then(function(response) {
            const projects = response.data;
            const tableBody = document.getElementById('projectsTable');
            tableBody.innerHTML = '';

            projects.forEach(function(project) {
                const row = document.createElement('tr');
                // 添加data-project-id属性到行元素，用于项目选择功能
                row.setAttribute('data-project-id', project.id);
                // 在loadProjects函数中修改按钮HTML生成部分
                row.innerHTML = `
                    <td>
                        <a href="/project/${project.id}" class="project-link">${project.id}</a>
                    </td>
                    <td class="project-name" data-project-id="${project.id}">${project.name}</td>
                    <td>${project.owner}</td>
                    <td>${project.type}</td>
                    <td>${project.platform}</td>
                    <td>${project.version}</td>
                    <td>${project.create}</td>
                    <td>${project.edit}</td>
                    <td>${project.publish}</td>
                    <td>${project.desc}</td>
                    <!--
                    <td>
                        <span class="status-badge ${getStatusClass(project.status)}">${project.status}</span>
                    </td>
                    -->
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-primary edit-project-btn" title="编辑" data-project-id="${project.id}">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-success run-project-btn" title="运行" data-project-id="${project.id}">
                                <i class="bi bi-play"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger delete-project-btn" title="删除" data-project-id="${project.id}">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 为项目名称添加点击编辑功能
            setupProjectNameEditing();
            setupProjectButtons();
        })
        .catch(function(error) {
            console.error('加载项目失败:', error);
            showNotification('加载项目失败', 'danger');
        });
}

function newProject() {
    // 显示模态框
    var newProjectModal = new bootstrap.Modal(document.getElementById('newProjectModal'));
    newProjectModal.show();

    // 处理确认按钮点击事件
    document.getElementById('createProjectBtn').addEventListener('click', function() {
        var projectName = document.getElementById('projectName').value;
        var projectType = document.getElementById('projectType').value;
        var projectPlatform = document.getElementById('projectPlatform').value;
        var projectVersion = document.getElementById('projectVersion').value;
        var projectDescription = document.getElementById('projectDescription').value;
    
        if (projectName && projectType && projectPlatform && projectVersion && projectDescription) {
            // 构建POST请求数据
            var postData = {
                name: projectName,
                type: projectType,
                platform: projectPlatform,
                version: projectVersion,
                desc: projectDescription,
            };
            // 发送POST请求创建新项目
            axios.post('/api/projects?api=new_project', postData)
                .then(function(response) {
                    var projectId = response.data.id;
                    // 跳转到新项目页面
                    window.location.href = '/project/' + projectId;
                })
                .catch(function(error) {
                    console.error('创建项目失败:', error);
                    showNotification('创建项目失败', 'danger');
                });
        } else {
            alert('请填写所有字段');
        }
    });
}

// 加载模板列表
function loadTemplates() {
    axios.get('/api/templates?api=get_templates')
        .then(function(response) {
            const templates = response.data.templates;
            const templatesGrid = document.getElementById('templatesGrid');
            templatesGrid.innerHTML = '';

            templates.forEach(function(template) {
                const card = document.createElement('div');
                card.className = 'template-card';
                card.innerHTML = `
                    <h3>${template.name}</h3>
                    <p>${template.description}</p>
                    <span class="category">${template.category}</span>
                `;
                card.addEventListener('click', function() {
                    createProjectFromTemplate(template.id);
                });
                templatesGrid.appendChild(card);
            });
        })
        .catch(function(error) {
            console.error('加载模板失败:', error);
            showNotification('加载模板失败', 'danger');
        });
}

// 加载任务列表
function loadTasks() {
    
}

// 加载设备列表
function loadDevices() {
    axios.get('/api/devices?api=get_devices')
        .then(function(response) {
            const devices = response.data.devices;
            const tableBody = document.getElementById('devicesTable');
            tableBody.innerHTML = '';

            devices.forEach(function(device) {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>
                        <a href="/device/${device.sn}" class="device-link">${device.name}</a>
                    </td>
                    <td>
                        <a href="/device/${device.sn}" class="device-link">${device.sn}</a>
                    </td>
                    <td>${device.type}</td>
                    <td>${device.ip}</td>
                    <td>${device.proxy}</td>
                    <td>
                        <span class="status-badge ${device.status === 'online' ? 'status-online' : 'status-offline'}">${device.status}</span>
                    </td>
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-primary" title="连接">
                                <i class="bi bi-link"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-success" title="安装应用">
                                <i class="bi bi-download"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-warning" title="烧录镜像">
                                <i class="bi bi-device-hdd"></i>
                            </button>
                        </div>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        })
        .catch(function(error) {
            console.error('加载设备失败:', error);
            showNotification('加载设备失败', 'danger');
        });
}

// 加载报告列表
function loadReports() {
    axios.get('/api/reports?api=get_reports')
        .then(function(response) {
            const reports = response.data.reports;
            const tableBody = document.getElementById('reportsTable');
            tableBody.innerHTML = '';

            reports.forEach(function(report) {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>
                        <a href="/report/${report.id}" class="report-link">${report.name}</a>
                    </td>
                    <td>${report.owner}</td>
                    <td>${report.testcase}</td>
                    <td>${report.device}</td>
                    <td>${report.created}</td>
                    <td>
                        <span class="status-badge ${getReportStatusClass(report.status)}">${report.status}</span>
                    </td>
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-primary" title="查看">
                                <i class="bi bi-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-secondary" title="导出">
                                <i class="bi bi-download"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger" title="删除">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        })
        .catch(function(error) {
            console.error('加载报告失败:', error);
            showNotification('加载报告失败', 'danger');
        });
}

// 从模板创建项目
function createProjectFromTemplate(templateId) {
    // 实际应用中应该发送请求到后端创建项目
    console.log('从模板创建项目:', templateId);
    showNotification('正在创建项目...', 'info');
    
    // 模拟创建项目后跳转
    setTimeout(function() {
        window.location.href = '/project/1';
    }, 1000);
}

// 设置搜索功能
function setupSearch() {
    const searchInputs = document.querySelectorAll('.search-input');
    searchInputs.forEach(function(input) {
        input.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const tabPane = this.closest('.tab-pane');
            
            if (tabPane.id === 'workspace') {
                filterTable('projectsTable', searchTerm);
            } else if (tabPane.id === 'template') {
                filterTemplates(searchTerm);
            } else if (tabPane.id === 'device') {
                filterTable('devicesTable', searchTerm);
            } else if (tabPane.id === 'report') {
                filterTable('reportsTable', searchTerm);
            }
        });
    });
}

// 过滤表格
function filterTable(tableId, searchTerm) {
    const rows = document.getElementById(tableId).getElementsByTagName('tr');
    for (let i = 0; i < rows.length; i++) {
        const rowText = rows[i].textContent.toLowerCase();
        rows[i].style.display = rowText.includes(searchTerm) ? '' : 'none';
    }
}

// 过滤模板
function filterTemplates(searchTerm) {
    const cards = document.querySelectorAll('.template-card');
    cards.forEach(function(card) {
        const cardText = card.textContent.toLowerCase();
        card.style.display = cardText.includes(searchTerm) ? '' : 'none';
    });
}

// 获取状态样式类
function getStatusClass(status) {
    switch (status) {
        case '活跃':
            return 'status-active';
        case '完成':
            return 'status-completed';
        case '暂停':
            return 'status-paused';
        default:
            return '';
    }
}

// 获取报告状态样式类
function getReportStatusClass(status) {
    switch (status) {
        case '通过':
            return 'status-passed';
        case '失败':
            return 'status-failed';
        case '部分通过':
            return 'status-partial';
        default:
            return '';
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <i class="bi ${getNotificationIcon(type)}"></i>
            <span>${message}</span>
        </div>
        <button class="notification-close">
            <i class="bi bi-x"></i>
        </button>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 添加关闭按钮事件
    notification.querySelector('.notification-close').addEventListener('click', function() {
        notification.remove();
    });
    
    // 自动关闭
    setTimeout(function() {
        notification.classList.add('notification-hide');
        setTimeout(function() {
            notification.remove();
        }, 300);
    }, 3000);
}

// 获取通知图标
function getNotificationIcon(type) {
    switch (type) {
        case 'success':
            return 'bi-check-circle';
        case 'danger':
            return 'bi-exclamation-triangle';
        case 'warning':
            return 'bi-exclamation-circle';
        case 'info':
        default:
            return 'bi-info-circle';
    }
}

// 防抖函数
function debounce(func, delay) {
    let timeout;
    return function(...args) {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), delay);
    };
}

// 初始化侧边栏折叠功能
function initSidebar() {
    const toggleBtn = document.getElementById('toggleSidebar');
    const sidebar = document.getElementById('sidebar');
    
    // 确保侧边栏默认为折叠状态
    if (!sidebar.classList.contains('collapsed')) {
        sidebar.classList.add('collapsed');
    }
    
    // 添加点击事件处理
    toggleBtn.addEventListener('click', function() {
        sidebar.classList.toggle('collapsed');
    });
}

// 设置项目名称原地编辑功能
function setupProjectNameEditing() {
    const projectNameCells = document.querySelectorAll('.project-name');
    
    projectNameCells.forEach(cell => {
        cell.addEventListener('click', function(event) {
            // 防止冒泡，避免点击输入框时触发事件
            event.stopPropagation();
            
            // 如果已经在编辑状态，则不再创建新的输入框
            if (this.querySelector('input')) return;
            
            const projectId = this.getAttribute('data-project-id');
            const currentName = this.textContent;
            
            // 保存原始单元格宽度
            const originalWidth = this.offsetWidth;
            
            // 创建输入框
            const input = document.createElement('input');
            input.type = 'text';
            input.value = currentName;
            input.className = 'form-control form-control-sm';
            // 保存原始名称到自定义属性
            input.dataset.originalName = currentName;
            
            // 优化编辑框样式，保持单元格尺寸
            input.style.width = '100%';  // 使用100%宽度填充单元格
            input.style.margin = '0';  // 移除边距
            input.style.padding = '2px 5px';  // 减小内边距
            input.style.boxSizing = 'border-box';  // 确保padding不会增加总宽度
            
            // 清空单元格并添加输入框
            this.textContent = '';
            this.appendChild(input);
            
            // 确保单元格宽度不变
            this.style.width = originalWidth + 'px';
            this.style.minWidth = originalWidth + 'px';
            this.style.maxWidth = originalWidth + 'px';
            
            // 自动聚焦输入框
            input.focus();
            
            // 处理输入框失去焦点事件
            input.addEventListener('blur', function() {
                handleProjectRename(this, projectId);
                // 恢复单元格样式
                cell.style.width = '';
                cell.style.minWidth = '';
                cell.style.maxWidth = '';
            });
            
            // 处理回车键事件
            input.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    handleProjectRename(this, projectId);
                    // 恢复单元格样式
                    cell.style.width = '';
                    cell.style.minWidth = '';
                    cell.style.maxWidth = '';
                }
            });
            
            // 处理ESC键事件（取消编辑）
            input.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    cell.textContent = currentName;
                    // 恢复单元格样式
                    cell.style.width = '';
                    cell.style.minWidth = '';
                    cell.style.maxWidth = '';
                }
            });
        });
    });
}

// 处理项目重命名
function handleProjectRename(inputElement, projectId) {
    const newName = inputElement.value.trim();
    const cell = inputElement.parentElement;
    const originalName = inputElement.dataset.originalName;
    
    // 如果名称为空，恢复原名称
    if (!newName) {
        cell.textContent = originalName;
        return;
    }
    
    // 如果名称没有变化，直接恢复显示
    if (newName === originalName) {
        cell.textContent = newName;
        return;
    }
    
    // 更新UI显示
    cell.textContent = newName;
    
    // 发送API请求更新项目名称
    axios.post('/api/projects?api=rename_project', {
        id: projectId,
        name: newName
    })
        .then(function() {
            showNotification(`项目已重命名为"${newName}"`, 'success');
        })
        .catch(function(error) {
            // 发生错误时恢复原名称
            cell.textContent = originalName;
            console.error('重命名项目失败:', error);
            showNotification('重命名项目失败，请稍后重试', 'danger');
        });
}

// 设置项目操作按钮事件处理
function setupProjectButtons() {
    // 编辑按钮事件处理
    document.querySelectorAll('.edit-project-btn').forEach(button => {
        button.addEventListener('click', function() {
            const projectId = this.getAttribute('data-project-id');
            openEditProjectModal(projectId);
        });
    });
    
    // 运行按钮事件处理
    document.querySelectorAll('.run-project-btn').forEach(button => {
        button.addEventListener('click', function() {
            const projectId = this.getAttribute('data-project-id');
            runProject(projectId);
        });
    });
    
    // 删除按钮事件处理
    document.querySelectorAll('.delete-project-btn').forEach(button => {
        button.addEventListener('click', function() {
            const projectId = this.getAttribute('data-project-id');
            confirmDeleteProject(projectId);
        });
    });
}

// 打开项目编辑模态框
function openEditProjectModal(projectId) {
    // 获取项目信息
    axios.get(`/api/projects?api=get_project_detail&id=${projectId}`)
        .then(function(response) {
            const project = response.data;
            
            // 如果模态框不存在，创建一个
            if (!document.getElementById('editProjectModal')) {
                const modalHTML = `
                <div class="modal fade" id="editProjectModal" tabindex="-1" aria-labelledby="editProjectModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="editProjectModalLabel">编辑项目</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                            </div>
                            <div class="modal-body">
                                <form id="editProjectForm">
                                    <input type="hidden" id="editProjectId">
                                    <div class="mb-3">
                                        <label for="editProjectName" class="form-label">项目名称</label>
                                        <input type="text" class="form-control" id="editProjectName" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="editProjectType" class="form-label">项目类型</label>
                                        <select class="form-select" id="editProjectType" required>
                                            <option value="Web">Web</option>
                                            <option value="Mobile">Mobile</option>
                                            <option value="Desktop">Desktop</option>
                                            <option value="API">API</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="editProjectPlatform" class="form-label">目标平台</label>
                                        <select class="form-select" id="editProjectPlatform" required>
                                            <option value="Android">Android</option>
                                            <option value="iOS">iOS</option>
                                            <option value="Windows">Windows</option>
                                            <option value="Linux">Linux</option>
                                            <option value="macOS">macOS</option>
                                            <option value="Web">Web</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="editProjectVersion" class="form-label">平台版本</label>
                                        <input type="text" class="form-control" id="editProjectVersion" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="editProjectDescription" class="form-label">项目描述</label>
                                        <textarea class="form-control" id="editProjectDescription" rows="3" required></textarea>
                                    </div>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" id="saveProjectBtn">保存</button>
                            </div>
                        </div>
                    </div>
                </div>
                `;
                
                // 添加模态框到页面
                const modalContainer = document.createElement('div');
                modalContainer.innerHTML = modalHTML;
                document.body.appendChild(modalContainer.firstElementChild);
                
                // 添加保存按钮事件 - 使用内联函数而不是直接引用saveProjectChanges
                const saveBtn = document.getElementById('saveProjectBtn');
                if (saveBtn) {
                    saveBtn.addEventListener('click', function() {
                        // 调用保存项目修改函数
                        if (typeof saveProjectChanges === 'function') {
                            saveProjectChanges();
                        } else {
                            console.error('saveProjectChanges函数未定义');
                            showNotification('保存功能暂时不可用', 'danger');
                        }
                    });
                }
            }
            
            // 确保表单元素存在后再填充数据
            const editProjectIdElement = document.getElementById('editProjectId');
            const editProjectNameElement = document.getElementById('editProjectName');
            const editProjectTypeElement = document.getElementById('editProjectType');
            const editProjectPlatformElement = document.getElementById('editProjectPlatform');
            const editPlatformVersionElement = document.getElementById('editProjectVersion');
            const editProjectDescriptionElement = document.getElementById('editProjectDescription');
            
            // 填充表单数据 - 添加存在性检查
            if (editProjectIdElement) editProjectIdElement.value = project.id;
            if (editProjectNameElement) editProjectNameElement.value = project.name;
            if (editProjectTypeElement) editProjectTypeElement.value = project.type;
            if (editProjectPlatformElement) editProjectPlatformElement.value = project.platform;
            if (editPlatformVersionElement) editPlatformVersionElement.value = project.version;
            if (editProjectDescriptionElement) editProjectDescriptionElement.value = project.desc;
            
            // 显示模态框 - 添加存在性检查
            const editProjectModalElement = document.getElementById('editProjectModal');
            if (editProjectModalElement) {
                const editProjectModal = new bootstrap.Modal(editProjectModalElement);
                editProjectModal.show();
            } else {
                console.error('模态框元素不存在');
                showNotification('无法显示编辑窗口', 'danger');
            }
        })
        .catch(function(error) {
            console.error('获取项目详情失败:', error);
            showNotification('获取项目详情失败', 'danger');
        });
}

// 保存项目修改
function saveProjectChanges() {
    const projectId = document.getElementById('editProjectId').value;
    const projectName = document.getElementById('editProjectName').value;
    const projectType = document.getElementById('editProjectType').value;
    const projectPlatform = document.getElementById('editProjectPlatform').value;
    const projectVersion = document.getElementById('editProjectVersion').value;
    const projectDescription = document.getElementById('editProjectDescription').value;
    
    // 验证表单
    if (!projectName || !projectType || !projectPlatform || !projectVersion || !projectDescription) {
        showNotification('请填写所有必填字段', 'warning');
        return;
    }
    
    // 构建请求数据
    const postData = {
        id: projectId,
        name: projectName,
        type: projectType,
        platform: projectPlatform,
        version: projectVersion,
        desc: projectDescription
    };
    
    // 发送更新请求
    axios.post('/api/projects?api=update_project', postData)
        .then(function() {
            // 关闭模态框
            const editProjectModal = bootstrap.Modal.getInstance(document.getElementById('editProjectModal'));
            editProjectModal.hide();
            
            // 显示成功通知
            showNotification('项目更新成功', 'success');
            
            // 重新加载项目列表
            loadProjects();
        })
        .catch(function(error) {
            console.error('更新项目失败:', error);
            showNotification('更新项目失败', 'danger');
        });
}

// 运行项目
function runProject(projectId) {
    // 显示加载通知
    showNotification('正在准备运行项目...', 'info');
    
    // 发送运行请求
    axios.post(`/api/projects?api=run_project`, {id: projectId})
        .then(function(response) {
            // 跳转到项目页面
            window.location.href = `/project/${projectId}?run=true`;
        })
        .catch(function(error) {
            console.error('运行项目失败:', error);
            showNotification('运行项目失败', 'danger');
        });
}

// 确认删除项目模态框
function confirmDeleteProject(projectId) {
    // 获取项目名称
    const projectName = document.querySelector(`.project-name[data-project-id="${projectId}"]`).textContent;
    
    // 创建确认删除模态框
    if (!document.getElementById('deleteProjectModal')) {
        const modalHTML = `
            <div class="modal fade" id="deleteProjectModal" tabindex="-1" aria-labelledby="deleteProjectModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="deleteProjectModalLabel">确认删除</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                        </div>
                        <div class="modal-body">
                            <p>您确定要删除项目 "<span id="deleteProjectName"></span>" 吗？</p>
                            <p class="text-danger">此操作不可撤销！</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 添加模态框到页面
        const modalContainer = document.createElement('div');
        modalContainer.innerHTML = modalHTML;
        document.body.appendChild(modalContainer.firstElementChild);
    }
    
    // 设置项目名称
    document.getElementById('deleteProjectName').textContent = projectName;
    
    // 显示模态框
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteProjectModal'));
    deleteModal.show();
    
    // 设置确认删除按钮事件
    const confirmBtn = document.getElementById('confirmDeleteBtn');
    // 移除可能存在的旧事件监听器
    const newConfirmBtn = confirmBtn.cloneNode(true);
    confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
    
    // 添加新的事件监听器
    newConfirmBtn.addEventListener('click', function() {
        deleteProject(projectId, deleteModal);
    });
}

// 删除项目
function deleteProject(projectId, modal) {
    axios.post(`/api/projects?api=delete_project`, {id: projectId})
        .then(function() {
            // 关闭模态框
            modal.hide();
            // 显示成功通知
            showNotification('项目已成功删除', 'success');
            // 重新加载项目列表
            loadProjects();
        })
        .catch(function(error) {
            // 关闭模态框
            modal.hide();
            console.error('删除项目失败:', error);
            showNotification('删除项目失败', 'danger');
        });
}